package com.zzsy.carosshopprojects.network.Utils;

import android.content.Intent;

import com.zzsy.carosshopprojects.base.BaseApplation;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 数据返回统一处理  参考https://www.jianshu.com/p/ff619fea7e22
 *
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
    private static final String TAG = "BaseObserver";

    @Override
    public void onNext(BaseResponse<T> response) {
        //在这边对 基础数据 进行统一处理  举个例子：
        if (response.getCode() == 200) {
            try {
                onSuccess(response.getData());
            } catch (Exception e) {
                String strData = response.getData() + "";
                onFailure(null, strData, response.getCode());
            }

        } else {
            if (response.getCode() == 300) {
                Intent intent = new Intent();
                intent.setAction("com.cyf.token");
                BaseApplation.instance().sendBroadcast(intent);
            }
            onFailure(null, response.getMsg(), response.getCode());

        }
    }

    @Override
    public void onError(Throwable e) {//服务器错误信息处理
        onFailure(e, RxExceptionUtil.exceptionHandler(e), 700);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onSubscribe(Disposable d) {
    }

    public abstract void onSuccess(T result);

    public abstract void onFailure(Throwable e, String errorMsg, int code);

}
